import eventEmitter from '@/utils/eventEmitter';
import type { Data } from '@/utils/http';
import { generateUniqueId } from '@/utils/generateUniqueId';

const base64ImgtoFile = (dataurl: string, filename = 'file') => {
  const arr = dataurl.split(',');
  // @ts-ignore
  const mime = arr[0].match(/:(.*?);/)[1];
  const suffix = mime.split('/')[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], `${filename}.${suffix}`, {
    type: mime,
  });
};

export const uploadFile = (files: any) => {
  return new Promise<Data<string>>((resolve, reject) => {
    uni.uploadFile({
      url: '/minio/upload',
      // #ifndef MP-WEIXIN
      file: base64ImgtoFile(files[0].url),
      // #endif
      filePath: files[0].url,
      name: 'file',
      formData: {
        fileId: generateUniqueId(),
      },
      success(result) {
        if (result.statusCode >= 200 && result.statusCode < 300) {
          // 获取数据成功，调用resolve
          eventEmitter.emit('API:UPLOAD_SUCCESS', result);
          const JSONPARSE = JSON.parse(result.data) as unknown as Data<string>;
          resolve(JSONPARSE);
        }
      },
      // 响应失败
      fail(err) {
        eventEmitter.emit('API:UPLOAD_FAIL');
        reject(err);
      },
    });
  });
};
